package com.m7788.adapter;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.imagemanager.util.MediaItem;
import com.m7788.screen.R;
import com.tool.custom.layout.SquareLayout;

public class GridAdapter extends BaseAdapter {

	private ArrayList<MediaItem> mediaSetList;
	private Context mContext;
	private LayoutInflater inflater;
	private boolean isMultiple = false;
	int w=100;
	int h=100;
	private OnGridAdapterChangeListener listener;
	public GridAdapter(Context context, ArrayList<MediaItem> list) {
		this.mediaSetList = list;
		this.mContext = context;
		inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//		VMRuntime.getRuntime().setMinimumHeapSize(16 * 1024 * 1024);   
//        VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);  
	}

	public void setOnGridAdapterChangeListener(
			OnGridAdapterChangeListener listener) {
		this.listener = listener;
	}

	public boolean isMultiple() {
		return isMultiple;
	}

	public void setMultiple(boolean isMultiple) {
		this.isMultiple = isMultiple;
//		notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		return mediaSetList.size();
	}

	@Override
	public Object getItem(int arg0) {
		return mediaSetList.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		return arg0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup arg2) {
		ViewHolder holder = null;
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.adapter_gridview, null);
			holder = new ViewHolder();
			holder.layout = (SquareLayout) convertView
					.findViewById(R.id.ag_main);
			holder.iv = (ImageView) convertView.findViewById(R.id.itemImage);
			
//			holder.iv.setOnClickListener(new MyOnClickListener(holder) {
//				@Override
//				public void onClick(View v, ViewHolder vholder) {
//					if (mediaSetList.size() > 1) {
//						int p = (Integer) vholder.civ.getTag();
//						MediaItem temp = mediaSetList.get(p);
//						if (temp.isCheck) {
//							temp.isCheck = false;
//						} else {
//							temp.isCheck = true;
//						}
//						mediaSetList.set(p, temp);
//						if (listener != null) {
//							listener.changeAdapterDate(p);
//						}
//					}
//				}
//			});

			holder.civ = (ImageView) convertView
					.findViewById(R.id.itemImageCheck);
			holder.civ.setTag(position);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
			holder.civ.setTag(position);
		}

		MediaItem item = mediaSetList.get(position);
		h=holder.iv.getHeight();
		w=holder.iv.getWidth();
		LayerDrawable bg = getView(item);
//		Log.e("",holder.iv.getHeight()+"-"+holder.iv.getWidth());
		holder.iv.setImageDrawable(bg);
		if (isMultiple) {
			holder.layout.setBackgroundDrawable(mContext.getResources()
					.getDrawable(R.drawable.stack_frame_focus));
		}
		
		return convertView;
	}

	public void addItem(MediaItem item) {
		if(mediaSetList != null){
			mediaSetList.add(item);
		}
	}

	public ArrayList<String> getSelectItemList() {
		ArrayList<String> list = new ArrayList<String>();
		for(MediaItem temp:mediaSetList){
			if(temp.isCheck){
				list.add(temp.mFilePath);
			}
		}
		
//		if (sort_flag==2){
//			ArrayList<String> list2 = new ArrayList<String>();		
//			int size = list.size()-1;
//			for(int i = size;i>=0;i--){
//				list2.add(list.get(i));
//			}
//			return list2;
//			
//
//			
//
//		}else{
			
			return list;
//		}
	
	}
	
	public ArrayList<Float> getSelectItemRotationList() {
		ArrayList<Float> list = new ArrayList<Float>();
		for(MediaItem temp:mediaSetList){
			if(temp.isCheck){
				list.add(temp.mRotation);
			}
		}
		return list;
	}
	
	public void changeDate(int posi){
		if (mediaSetList.size() > 1) {
			MediaItem temp = mediaSetList.get(posi);
			if (temp.isCheck) {
				temp.isCheck = false;
			} else {
				temp.isCheck = true;
			}
			mediaSetList.set(posi, temp);
			if (listener != null) {
				listener.changeAdapterDate(posi);
			}
			notifyDataSetChanged();
		}
	}
	
	public void clearSelect(){
		for(int i =0;i<mediaSetList.size();i++){
			MediaItem temp = mediaSetList.get(i);
			temp.isCheck=false;
			mediaSetList.set(i, temp);
		}
		notifyDataSetChanged();
	}

	public void clearMemory(){
		
//		for(int i =0;i<mediaSetList.size();i++){
//			MediaItem temp = mediaSetList.get(i);
//			if(temp.mThumbnailBitmap != null && !temp.mThumbnailBitmap.isRecycled()){
//				temp.mThumbnailBitmap.recycle();
//				temp.mThumbnailBitmap = null;
//			}
//			
//		}
		clearList();
		mediaSetList = null;
		System.gc();
	}
	public void clearList(){
		if(mediaSetList.size()>0){
			for(int i=mediaSetList.size()-1;i>=0;i--){
				mediaSetList.remove(i);
			}
		}
	}
	private final class ViewHolder {
		private TextView attr0;
		private ImageView iv;
		private ImageView civ;
		private SquareLayout layout;
	}

	private abstract class MyOnClickListener implements View.OnClickListener {

		private ViewHolder mViewHolder;

		public MyOnClickListener(ViewHolder viewHolder) {
			mViewHolder = viewHolder;
		}

		@Override
		public void onClick(View v) {
			onClick(v, mViewHolder);

		}

		public abstract void onClick(View v, ViewHolder viewHolder);

	}

	public interface OnGridAdapterChangeListener {
		/**
		 * 
		 * 方法名：listRemove 功能：减少项 参数：
		 * 
		 * @param currentItem
		 *            创建人：huanghsh 创建时间：2012-6-8
		 */
		public void changeAdapterDate(int currentItem);
	}

	
	private LayerDrawable getView(MediaItem item) {

		Bitmap bitmap2 = null;
		Bitmap ro = null;
		LayerDrawable la = null;
		if (item.isCheck == true) {
			bitmap2 = BitmapFactory.decodeResource(mContext.getResources(),
					R.drawable.as_select_on);
		}
		ro = rotationn(item);
		if (bitmap2 != null) {
			
			Drawable[] array = new Drawable[2];
			array[0] = new BitmapDrawable(ro);
			array[1] = new BitmapDrawable(bitmap2);
			la = new LayerDrawable(array);
			la.setLayerInset(0, 0, 0, 0, 0); // 第几张图离各边的间距
			la.setLayerInset(1, w-40, 4, 4, h-40);
		} else {
			Drawable[] array = new Drawable[1];
			array[0] = new BitmapDrawable(ro);
			la = new LayerDrawable(array);
			la.setLayerInset(0, 0, 0, 0, 0);
		}
//		if(ro!=null && !ro.isRecycled()){ ro.recycle(); ro = null;}
		System.gc();
		return la; // 返回叠加后的图
	}
	
	private Bitmap rotationn( MediaItem item){
		Bitmap bitmap = item.mThumbnailBitmap;
		float angle = item.mRotation;
		if(bitmap==null){
			bitmap = decodeFile(item.mFilePath);
		}
		Matrix m = new Matrix();  
		if(bitmap!=null ){
	        int width = bitmap.getWidth();  
	        int height = bitmap.getHeight();  
	        m.setRotate(angle); // 旋转angle度  
	        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height,  
	                m, true);// 从新生成图片  
		}
        return bitmap;
	}
	
	
	private Bitmap decodeFile(String path) {
        // decode image size
		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inJustDecodeBounds = true;
		// Find the correct scale value. It should be the power of 2.
		int width_tmp = o.outWidth, height_tmp = o.outHeight;
		int scale = 1;
		while (true) {
		        if (width_tmp / 2 < 100
		                        || height_tmp / 2 < 100)
		                break;
		        width_tmp /= 2;
		        height_tmp /= 2;
		        scale *= 2;
		}

		// decode with inSampleSize
		BitmapFactory.Options o2 = new BitmapFactory.Options();
		o2.inSampleSize = scale;
		return BitmapFactory.decodeFile(path,o);
}
}
